package com.yd.sdk.payimp;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.PurchaseHistoryResponseListener;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.yd.sdk.pay.PayAbstractClass;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PayImp extends PayAbstractClass {
    public final String TAG = "PayImp";

    //支付实例
    private BillingClient _billingClient;
    //断线重连次数
    private int MAX_RELOAD_TIMES = 1;
    private int _currentReloadTimes = 0;
    //是否开始连接,不重复连接
    private boolean _isStartConnect = false;
    //查询商品列表
    private List<String> _inApp_List = new ArrayList<>();
    //查询订阅列表
    private List<String> _subs_List = new ArrayList<>();
    //查询商品列表中的表示非消耗型的商品列表
    private List<String> _nonConsumeSkuList = new ArrayList<>();
    //所有的Sku列表
    private List<SkuDetails> _allSkuDetails = new ArrayList<>();
    //用来判断重复订阅,就是订阅的升级,叠加购买(1个月1个月的买)
    private  Map<String,String> _cacheSubsPurchaseTokens = new HashMap<String,String>();

    private boolean _isQueryINAPP = false;
    private boolean _isQuerySUBS = false;

    //此监听器可接收应用中所有购买交易的更新。
    private PurchasesUpdatedListener _purchasesUpdatedListener = new PurchasesUpdatedListener() {
        @Override
        public void onPurchasesUpdated(BillingResult billingResult,  List<Purchase> purchases) {
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                    && purchases != null) {
                for (Purchase purchase : purchases) {
                    //3.0
                    HandlePurchase(purchase,IsSubs(purchase.getSku())? BillingClient.SkuType.SUBS:BillingClient.SkuType.INAPP);
                    //4.0
                    //HandlePurchase(purchase,IsSubs(purchase.getSkus().get(0))? BillingClient.SkuType.SUBS:BillingClient.SkuType.INAPP);
                }
            } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) {
                // Handle an error caused by a user cancelling the purchase flow.
//                Log.e("Hello Billing","BillingClient UserCanceled!");
            } else {
                // Handle any other error codes.
//                Log.e("Hello Billing","BillingClient Other Error!");
            }
        }
    };

    @Override
    public void onCreate(Activity activity, Bundle savedInstanceState) {
        this.activity = activity;
    }

    @Override
    public void Initialized(String ConsumeSku, String NonConsumeSku, String SubsSku) {

        Log.e(TAG,"Initialized=>" +ConsumeSku +"," + NonConsumeSku+","+SubsSku);
        String[] consumeArray = ConsumeSku.trim().split(",");
        String[] nonConsumeArray = NonConsumeSku.trim().split(",");
        String[] subsArray = SubsSku.trim().split(",");

        if(consumeArray!=null)
        {
            for (String item : consumeArray)
            {
                if(!"".equals(item))
                    _inApp_List.add(item);
            }
//            _inApp_List.addAll(Arrays.asList(consumeArray));
        }

        if(nonConsumeArray!=null)
        {
            for (String item : nonConsumeArray)
            {
                if(!"".equals(item))
                {
                    _inApp_List.add(item);
                    _nonConsumeSkuList.add(item);
                }
            }

        }

        if(subsArray != null)
        {
            for (String item : subsArray)
            {
                if(!"".equals(item))
                    _subs_List.add(item);
            }

        }

        //STEP1. 初始化billingClient
        _billingClient = BillingClient.newBuilder(activity)
                .setListener(_purchasesUpdatedListener)
                .enablePendingPurchases()
                .build();
        //STEP2. 建立连接
        StartConnection();
    }

    //与 Google Play 建立连接
    private void StartConnection()
    {
//        Log.e(TAG,"StartConnection");
        if(_billingClient == null ||_isStartConnect || _billingClient.isReady())return;
        _isStartConnect = true;
        _billingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(BillingResult billingResult) {
                _isStartConnect = false;
                int responseCode = billingResult.getResponseCode();
                String debugMessage = billingResult.getDebugMessage();

                if (billingResult.getResponseCode() ==  BillingClient.BillingResponseCode.OK) {
                    Log.e(TAG,"onBillingSetupFinished====>OK");
                    // The BillingClient is ready. You can query purchases here.
                    //STEP3. 查询商品
                    QuerySkuDetails(_inApp_List, BillingClient.SkuType.INAPP);
                    //STEP4. 查询订阅
                    if(_subs_List.size() <=0)
                        _isQuerySUBS = true;
                    else
                        QuerySkuDetails(_subs_List, BillingClient.SkuType.SUBS);
                    //QueryPurchases();
                }else
                {
                    Log.e(TAG,"onBillingSetupFinished====>Failed" +responseCode +"," + debugMessage);
                }

            }
            @Override
            public void onBillingServiceDisconnected() {
                _isStartConnect = false;
                // Try to restart the connection on the next request to
                // Google Play by calling the startConnection() method.
                if (_currentReloadTimes < MAX_RELOAD_TIMES) {
                    ++_currentReloadTimes;
                    StartConnection();
                }else{
                    Log.e("Hello Billing", "Problem setting up in-app billing: " );
                    //触发通知Unity
                    OnIAPServerDisconnected();
                }
            }
        });
    }


    /**
     * 商品查询
     * @param list
     * @param type
     */
    private void QuerySkuDetails(List<String> list , String type)
    {
        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(list).setType(type);
        _billingClient.querySkuDetailsAsync(params.build(),
                new SkuDetailsResponseListener() {
                    @Override
                    public void onSkuDetailsResponse(BillingResult billingResult,
                                                     List<SkuDetails> skuDetailsList) {
                        // Process the result.
                       Log.e(TAG,"onSkuDetailsResponse=>>" + billingResult.getResponseCode() +"," + billingResult.getDebugMessage());
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)
                        {
                            switch (type) {
                                case BillingClient.SkuType.INAPP:
                                    _isQueryINAPP = true;
                                    break;
                                case BillingClient.SkuType.SUBS:
                                    _isQuerySUBS = true;
                                    break;
                            }

                            if(_isQueryINAPP && _isQuerySUBS)
                                OnIAPSetUpSuccess();

                            if(skuDetailsList == null)return;
                            _allSkuDetails.addAll(skuDetailsList);

                            //STEP5、6. 查询SKU购买情况
                            QueryPurchases(type);
                        }else
                            OnIAPSetUpFailed(billingResult.getResponseCode()+":"+billingResult.getDebugMessage());
                    }
                });
    }


    /**
     * 查询google商店应用所缓存的购买交易，不会发起网络请求
     * @param type
     */
    private void QueryPurchases(String type)
    {
        Purchase.PurchasesResult result = _billingClient.queryPurchases(type);
        if (result == null) {
            Log.i(TAG, "queryPurchases: null purchase result");
        } else {
            if (result.getPurchasesList() == null) {
              Log.i(TAG, "queryPurchases: null purchase list");
                //processPurchases(null);
            } else {
               Log.i(TAG, "queryPurchases: " +result.getPurchasesList().size());
                for (Purchase purchase : result.getPurchasesList())
                {
                    //STEP7. 查询SKU购买情况_InAPP
                    //STEP8. 查询SKU购买情况_SUBS
                    HandlePurchase(purchase,type);
                }
//                switch (type)
//                {
//                    case BillingClient.SkuType.INAPP:
//                        for (Purchase purchase : result.getPurchasesList())
//                        {
//                            //STEP7. 查询SKU购买情况
//                            HandlePurchase(purchase,BillingClient.SkuType.INAPP);
//                        }
//                        break;
//                    case BillingClient.SkuType.SUBS:
//                        for (Purchase purchase : result.getPurchasesList())
//                        {
//                            //STEP8. 查询SKU购买情况
//                            HandlePurchase(purchase,BillingClient.SkuType.SUBS);
//                        }
//                        break;
//                }
            }
        }
    }


    /**
     * 购买成功确认
     * @param purchase
     * @param type
     */
    private void HandlePurchase(Purchase purchase,String type)
    {
        //STEP6. 处理购买
        if(purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED)
        {
            //3.0
            Log.d(TAG, "handlePurchase PENDING: " + purchase.getSku());
            //4.0
//            Log.d(TAG, "handlePurchase PENDING: " + purchase.getSkus().get(0));
            switch (type)
            {
                case BillingClient.SkuType.INAPP:

                    //3.0 //4.0
                    if(IsNonConsumeInAPP(purchase.getSku()))
                    {
                        if(!purchase.isAcknowledged()) AcknowledgePurchase(purchase);
                    }else
                        ConsumePurchase(purchase);

//                    //if(IsNonConsumeInAPP(purchase.getSkus().get(0)))
//
//                        else
                    break;
                case BillingClient.SkuType.SUBS:
                    if(!purchase.isAcknowledged()) AcknowledgePurchase(purchase);
                    else
                    {
                        if(_cacheSubsPurchaseTokens.containsKey(purchase.getSku()))
                            _cacheSubsPurchaseTokens.remove(purchase.getSku());
                        _cacheSubsPurchaseTokens.put(purchase.getSku(),purchase.getPurchaseToken());

                        //需要更新购买令牌
//                        if(_cacheSubsPurchaseTokens.containsKey(purchase.getSkus().get(0)))
//                            _cacheSubsPurchaseTokens.remove(purchase.getSkus().get(0));
//                        _cacheSubsPurchaseTokens.put(purchase.getSkus().get(0),purchase.getPurchaseToken());
                    }

                    break;
            }

        }else if(purchase.getPurchaseState() == Purchase.PurchaseState.PENDING)
        {
//            Log.d(TAG, "handlePurchase PENDING: " + purchase.getSkus().get(0));
//            Log.d(TAG, "handlePurchase PENDING: " + purchase.getSkus().get(0));
        }
    }

    /**
     *  处理订阅以及非消耗商品
     * @param purchase
     */
    private void AcknowledgePurchase(Purchase purchase)
    {
        AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener = new AcknowledgePurchaseResponseListener()
        {
            @Override
            public void onAcknowledgePurchaseResponse(BillingResult billingResult)
            {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)
                {
                    OnIAPPurchaseSuccess(purchase.getSku());
                    //需要更新购买令牌
                    if(_cacheSubsPurchaseTokens.containsKey(purchase.getSku()))
                        _cacheSubsPurchaseTokens.remove(purchase.getSku());
                    _cacheSubsPurchaseTokens.put(purchase.getSku(),purchase.getPurchaseToken());
                }

                else
                    OnIAPPurchaseFailed(purchase.getSku(),billingResult.getResponseCode()+":"+billingResult.getDebugMessage());
            }
        };
        AcknowledgePurchaseParams acknowledgePurchaseParams =
                AcknowledgePurchaseParams.newBuilder()
                        .setPurchaseToken(purchase.getPurchaseToken())
                        .build();
        _billingClient.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);
    }

    private void ConsumePurchase(Purchase purchase)
    {
        ConsumeResponseListener listener = new ConsumeResponseListener() {
            @Override
            public void onConsumeResponse(BillingResult billingResult, String s) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)
                    OnIAPPurchaseSuccess(purchase.getSku());
                else
                    OnIAPPurchaseFailed(purchase.getSku(),billingResult.getResponseCode()+":"+billingResult.getDebugMessage());
            }
        };
        ConsumeParams consumeParams = ConsumeParams.newBuilder()
                .setPurchaseToken(purchase.getPurchaseToken())
                .build();
        // 消耗商品
        _billingClient.consumeAsync(consumeParams, listener);
    }


    @Override
    public void onPause() {

    }

    @Override
    public void onResume() {

    }

    @Override
    public void onDestroy() {
        if(_billingClient!=null && _billingClient.isReady())
            _billingClient.endConnection();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantRes) {

    }


    @Override
    public void PurchaseProduct(String productInfo) {
//        Log.e(TAG,productInfo);
        SkuDetails skuDetails = GetSkuDetailByName(productInfo);
        Boolean isSubs = IsSubs(productInfo);
        if(skuDetails!= null) {
            BillingFlowParams.Builder builder = BillingFlowParams.newBuilder();
            builder.setSkuDetails(skuDetails);
            if(_cacheSubsPurchaseTokens.containsKey(productInfo))
            {
                //如果是升降级的话  需要传老的
                builder.setOldSku(productInfo,_cacheSubsPurchaseTokens.get(productInfo));
//                BillingFlowParams.SubscriptionUpdateParams.Builder build1 = BillingFlowParams.SubscriptionUpdateParams.newBuilder();
//                build1.setOldSkuPurchaseToken(_cacheSubsPurchaseTokens.get(productInfo));
//                builder.setSubscriptionUpdateParams(build1.build());
            }

//            BillingFlowParams flowParams = builder.build();
            BillingResult result = _billingClient.launchBillingFlow(activity, builder.build());
            if (result.getResponseCode() == BillingClient.BillingResponseCode.OK)
            {
                // 调起支付界面成功
//                Log.e(TAG,result.getResponseCode() +":"+result.getDebugMessage());
            }
            else
            {
                // 调起支付界面失败
//                Log.e(TAG,"Error launching purchase flow isSetupDone."+result.getResponseCode());
                OnIAPPurchaseFailed(productInfo, result.getResponseCode() +":"+result.getDebugMessage());
            }
        }

    }

    @Override
    public int GetConnectionState() {

        return 0;
       // _billingClient.
//        return 0;
//        return  _billingClient.getConnectionState();
    }

    @Override
    public void QueryPurchaseHistory()
    {
        PurchaseHistoryResponseListener listener = new PurchaseHistoryResponseListener() {
            @Override
            public void onPurchaseHistoryResponse(BillingResult billingResult, List<PurchaseHistoryRecord> list) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)
                {
                    StringBuffer sb = new StringBuffer();
                    //查询成功
                    for (int i = 0;i<list.size();i++) {
                        sb.append(list.get(i).getSku());
                        sb.append(",");
                    }
                    OnQueryPurchaseHistorySucess(sb.toString());
                }
                else
                {
                    //查询历史记录失败
                    OnQueryPurchaseHistoryFailed(billingResult.getResponseCode() +":"+billingResult.getDebugMessage());
                }
            }
        };

        if(_billingClient.isReady())_billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP,listener);

    }


    //////////////////////为了方便/////////////////////////////////////
    private SkuDetails GetSkuDetailByName(String name)
    {
        SkuDetails result = null;
        for (SkuDetails skuDetails: _allSkuDetails) {
            if(skuDetails.getSku().equals(name))
            {
                result = skuDetails;
                break;
            }
        }
        return result;
    }

    /**
     * 判断是否是非消耗商品
     * @param skuName
     * @return
     */
    private boolean IsNonConsumeInAPP(String skuName)
    {
        boolean result = false;
        for (String name: _nonConsumeSkuList) {
            if(name.equals(skuName))
            {
                result = true;
                break;
            }
        }

        return result;
    }


    /**
     * 判断是否是订阅
     * @param skuName
     * @return
     */
    private boolean IsSubs(String skuName)
    {
        boolean result = false;
        for (String name : _subs_List)
        {
            if(name.equals(skuName))
            {
                result = true;
                break;
            }
        }

        return result;

    }



    ///////////////////////////////////////////////////////////////////////


}
